package com.xx.service.impl;

import com.xx.bean.Cart;
import com.xx.bean.CartItem;
import com.xx.bean.Order;
import com.xx.bean.User;
import com.xx.constant.BookStoreConstants;
import com.xx.mapper.BookMapper;
import com.xx.mapper.OrderMapper;
import com.xx.service.OrderService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class OrderServiceImpl implements OrderService {

    public static OrderMapper getSqlSession() throws IOException {
        String resource = "mybatis-config.xml";
        //读取类路径下的配置文件得到输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象，相当于Connection对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession.getMapper(OrderMapper.class);
    }

    @Override
    public String checkout(User user, Cart cart) throws IOException {
        OrderMapper mapper = getSqlSession();
        Order order = new Order();
        //生成随机的订单号
        String orderSequence = UUID.randomUUID().toString();
        order.setOrderSequence(orderSequence);
        //生成订单日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = dateFormat.format(new Date());
        order.setCreateTime(createTime);
        //cart中的TotalCount
        order.setTotalCount(cart.getTotalCount());
        //cart中的TotalAmount
        order.setTotalAmount(cart.getTotalAmount());
        //设置订单状态
        order.setOrderStatus(BookStoreConstants.UNFINLLEDORDER);
        //设置订单的用户id
        order.setUserId(user.getUserId());
        mapper.insertOrder(order);

//        Map<Integer, CartItem> cartItemMap = cart.getCartItemMap();
//        Collection<CartItem> cartItemCollection = cartItemMap.values();
//        ArrayList<CartItem> cartItemList = new ArrayList<>(cartItemCollection);
//        Object[][] insertOrderItemParamArr = new Object[cartItemList.size()][6];

        return null;
    }
}
